package com.suning.park.admin.mgr.merchant.service.impl;

import com.suning.park.admin.mgr.merchant.service.MerchantService;
import com.suning.park.admin.util.StringUtil;
import com.suning.park.admin.util.page.PageInfo;
import com.suning.park.dto.dao.MerchantMapper;
import com.suning.park.dto.dao.MerchantUserMapper;
import com.suning.park.dto.dao.SysUserMapper;
import com.suning.park.dto.model.Merchant;
import com.suning.park.dto.model.MerchantUser;
import com.suning.park.dto.model.SysUserExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * Created by Administrator on 2017/1/16.
 */
@Service
public class MerchantServiceImpl implements MerchantService {

    private final static Logger logger = LoggerFactory.getLogger(MerchantServiceImpl.class);

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    MerchantMapper merchantMapper;

    @Autowired
    MerchantUserMapper merchantUserMapper;

    @Override
    public PageInfo queryByPage(Map<String, Object> params, PageInfo page) {
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(params.get("merchantId").toString())) {
            criteria.andUserIdEqualTo(params.get("merchantId").toString());
        }
        //需要改为枚举
        criteria.andTypeEqualTo("0");
        int total = sysUserMapper.countByExample(example);
        page.setTotalResult(total);
        example.setLimitStart((page.getCurrentPage() - 1) * page.getShowCount());
        example.setLimitRows(page.getShowCount());
        page.setResultObject(sysUserMapper.selectByExample(example));
        return page;
    }

    @Override
    @Transactional
    public int update(Merchant merchant) {
        return merchantMapper.updateByPrimaryKeySelective(merchant);
    }

    @Override
    @Transactional
    public int add(Merchant merchant) {
        return merchantMapper.insert(merchant);
    }

    /**
     * 根据商户用户ID查找对应的商户信息
     * @param userId 商户用户ID
     * @return 查询成功返回商户信息，失败返回NULL
     */
    @Override
    public Merchant find(String userId) {
        MerchantUser marchantUser = merchantUserMapper.selectByPrimaryKey(userId);
        if (marchantUser != null) {
            return merchantMapper.selectByPrimaryKey(marchantUser.getMerchantId());
        } else {
            return null;
        }
    }
}
